﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;
using System.Windows.Forms;

namespace embed_window
{
    public class ExeImpaction
    {
        Process process = null;
        IntPtr appWin;

        [DllImport("user32.dll", SetLastError = true)]
        private static extern long SetParent(IntPtr hWndChild, IntPtr hWndNewParent);
        [DllImport("user32.dll", SetLastError = true)]
        private static extern IntPtr FindWindow(string lpClassName, string lpWindowName);
        [DllImport("user32.dll", SetLastError = true)]
        private static extern long SetWindowPos(IntPtr hwnd, long hWndInsertAfter, long x, long y, long cx, long cy, long wFlags);
        [DllImport("user32.dll", SetLastError = true)]
        private static extern bool MoveWindow(IntPtr hwnd, int x, int y, int cx, int cy, bool repaint);
        [DllImport("user32.dll", EntryPoint = "ShowWindow", SetLastError = true)]
        static extern bool ShowWindow(IntPtr hWnd, uint nCmdShow);

        /// <summary>
        /// 打开一个exe程序 并嵌入到窗体
        /// </summary>
        /// <param name="control">父类窗体</param>
        /// <param name="exePath">程序路径</param>
        /// <param name="frmCaption">窗体名称</param>
        /// <param name="args">参数们</param>
        /// <param name="waitSecond">等待时间（单点登录时如果窗体还没创建得到句柄是0无法显示窗体要等到他生成再显示）</param>
        /// <returns></returns>
        public string ExecExe(Control control, string exePath)
        {
            string errStr = "";
            try

            {
                ProcessStartInfo info = null;

                //if ((args ?? "").ToString() != "")
                //    info = new ProcessStartInfo(exePath, args);
                //else
                //    info = new ProcessStartInfo(exePath);

                info = new ProcessStartInfo(exePath);
                info.UseShellExecute = true;
                info.CreateNoWindow = true;
                info.WindowStyle = ProcessWindowStyle.Minimized;

                process = Process.Start(info);

                appWin = IntPtr.Zero;
                while (appWin == IntPtr.Zero)
                {
                    appWin = FindWindow(null, GetWindowName(process.ProcessName));
                    Thread.Sleep(200);
                }
                //appWin = User32API.GetWindowHandle((uint)process.Id);
            }
            catch (Exception ex)
            {
                throw ex;
            }

            SetParent(appWin, control.Handle);
            MoveWindow(appWin, 0, 0, control.Width, control.Height, true);
            ShowWindow(appWin, 1);

            return errStr;
        }

        public delegate bool EnumWindowsCallBack(IntPtr hwnd, uint lParam);
        [DllImport("user32.dll", SetLastError = true, CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)]
        public static extern int EnumChildWindows(IntPtr hWndParent, EnumWindowsCallBack lpfn, int lParam);
        [DllImport("user32.dll")]
        public static extern int GetWindowTextLength(IntPtr hWnd);
        [DllImport("User32.dll", CharSet = CharSet.Auto)]
        public static extern int GetWindowText(IntPtr hWnd, StringBuilder text, int nMaxCount);

        private List<string> childWnds = new List<string>();

        public string[] EnumChildWindows()
        {
            if (appWin == IntPtr.Zero) return null;
            childWnds.Clear();
            EnumChildWindows(appWin, EnumchildWindowCallback, 0);
            return childWnds.ToArray();
        }

        private bool EnumchildWindowCallback(IntPtr hwnd, uint lParam)
        {
            int length = GetWindowTextLength(hwnd);
            var buffer = new StringBuilder();
            GetWindowText(hwnd, buffer, length + 1);
            childWnds.Add(hwnd + " : " + buffer.ToString());
            return true;
        }

        /// <summary>
        /// 父窗体关闭方法
        /// </summary>
        public void FrmClosing()
        {
            try
            {
                if (!process.HasExited)
                    process.Kill();
            }
            catch
            {
            }
        }

        /// <summary>
        /// 父窗体尺寸改变方法
        /// </summary>
        /// <param name="frm"></param>
        public void FrmResize(Control frm)
        {
            if (this.appWin != IntPtr.Zero)
                MoveWindow(appWin, 0, 0, frm.Width, frm.Height, true);
        }

        private string GetWindowName(string exeName)
        {
            string str = exeName.ToUpper();
            switch (str)
            {
                case "TYPORA":
                    return exeName.ToUpper();
                case "NOTEPAD++":
                    return "new 1 - Notepad++";
                case "NOTEPAD":
                    return "无标题 - 记事本";

            }
            return exeName;
        }

    }
}